'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import dynamic from 'next/dynamic';
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Card, CardContent } from "@/components/ui/card"
import { motion } from "framer-motion";
import { Loader2, Wand2, HelpCircle } from "lucide-react";
import {
  Modal,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalTitle,
} from "@/components/ui/modal"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { useLanguage } from '@/contexts/LanguageContext';
import { useToast } from "@/hooks/use-toast";

const Select = dynamic(() => import('react-select'), {
  ssr: false
});

const CreatableSelect = dynamic(() => import('react-select/creatable'), {
  ssr: false
});

export default function NewPrompt() {
  const { language, t } = useLanguage();
  const { toast } = useToast();
  const router = useRouter();
  const { data: session } = useSession();

  // 1. 确保初始状态完全为空
  const [prompt, setPrompt] = useState({
    title: '',
    content: '',
    description: '',
    tags: 'Agent',  // 确保是完全空字符串
    version: '1.0.0',
  });
  
  // 修复：将 tagOptions 声明移到使用之前
  const [tagOptions, setTagOptions] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState({});
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [optimizedContent, setOptimizedContent] = useState('');
  const [showOptimizeModal, setShowOptimizeModal] = useState(false);
  const [showModelConfig, setShowModelConfig] = useState(false);
  const [modelConfig, setModelConfig] = useState({
    channel: '',
    channel_id: null,
    model: '',
    temperature: 1.0,
    max_tokens: 2048,
    top_p: 1.0,
    presence_penalty: 0.0,
    frequency_penalty: 0.0,
    n: 1,
    stop: '',
    logit_bias: '',
    stream: true,
    reasoning_effort: '',
    api_key: ''
  });

  const [channels, setChannels] = useState([]);
  const [models, setModels] = useState([]);

  const validateModelConfig = () => {
    // 渠道名称必填
    if (!modelConfig.channel || modelConfig.channel.trim() === '') {
      toast({ variant: 'destructive', description: '渠道名称不能为空' });
      return false;
    }
    // 模型名称必填
    if (!modelConfig.model || modelConfig.model.trim() === '') {
      toast({ variant: 'destructive', description: '模型名称不能为空' });
      return false;
    }
    // temperature [0,2]
    const temperature = Number(modelConfig.temperature);
    if (Number.isNaN(temperature) || temperature < 0 || temperature > 2) {
      toast({ variant: 'destructive', description: 'temperature 取值范围应在 [0, 2]' });
      return false;
    }
    // top_p [0,2]
    const top_p = Number(modelConfig.top_p);
    if (Number.isNaN(top_p) || top_p < 0 || top_p > 2) {
      toast({ variant: 'destructive', description: 'top_p 取值范围应在 [0, 2]' });
      return false;
    }
    // max_tokens [10,30000]
    const max_tokens = Number(modelConfig.max_tokens);
    if (Number.isNaN(max_tokens) || max_tokens < 10 || max_tokens > 30000) {
      toast({ variant: 'destructive', description: 'max_tokens 取值范围应在 [10, 30000]' });
      return false;
    }
    // presence_penalty [-2,2]
    const presence_penalty = Number(modelConfig.presence_penalty);
    if (Number.isNaN(presence_penalty) || presence_penalty < -2 || presence_penalty > 2) {
      toast({ variant: 'destructive', description: 'presence_penalty 取值范围应在 [-2.0, 2.0]' });
      return false;
    }
    // frequency_penalty [-2,2]
    const frequency_penalty = Number(modelConfig.frequency_penalty);
    if (Number.isNaN(frequency_penalty) || frequency_penalty < -2 || frequency_penalty > 2) {
      toast({ variant: 'destructive', description: 'frequency_penalty 取值范围应在 [-2.0, 2.0]' });
      return false;
    }
    return true;
  };

  // 2. 增强useEffect，添加日志并确保不会自动设置标签
  useEffect(() => {
    console.log('Initial tags state:', prompt.tags); // 调试日志
    fetch('/api/tags')
      .then((response) => response.json())
      .then((data) => {
        console.log('Fetched tags:', data); // 查看获取到的标签
        const mappedTags = data.map(tag => ({ value: tag.name, label: tag.name }));
        setTagOptions(mappedTags);
        // 完全移除自动设置默认标签的逻辑
        // 确保不会自动设置任何标签
      })
      .catch((error) => console.error('Error fetching tags:', error));
  }, [prompt.tags]);

  // 获取渠道信息
  useEffect(() => {
    const fetchChannels = async () => {
      if (!session?.user?.accessToken) return;
      
      try {
        const response = await fetch(`/api/models/channels`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setChannels(data.data);
        }
      } catch (error) {
        console.error('Error fetching channels:', error);
      }
    };

    fetchChannels();
  }, [session?.user?.accessToken]);

  // 当渠道改变时，获取对应的模型列表
  useEffect(() => {
    const fetchModels = async () => {
      if (!modelConfig.channel_id || !session?.user?.accessToken) {
        setModels([]);
        return;
      }

      try {
        const response = await fetch(`/api/models/models/${modelConfig.channel_id}`, {
          headers: {
            'Authorization': `Bearer ${session.user.accessToken}`
          }
        });
        const data = await response.json();
        if (data.code === 200 && data.data) {
          setModels(data.data);
        }
      } catch (error) {
        console.error('Error fetching models:', error);
      }
    };

    fetchModels();
  }, [modelConfig.channel_id, session?.user?.accessToken]);

  // 移除重复的状态声明和useEffect

  if (!t) return null;
  const tp = t.newPromptPage;

  const validateForm = () => {
    const newErrors = {};
    if (!prompt.title.trim()) newErrors.title = tp.errorTitleRequired;
    if (!prompt.content.trim()) newErrors.content = tp.errorContentRequired;
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) return;
    setIsSubmitting(true);

    try {
      // 校验模型配置（必填项及范围）
      if (!validateModelConfig()) {
        setIsSubmitting(false);
        return;
      }

      // 检查标题+版本号是否重复
      const checkResponse = await fetch(`/api/prompts/check-duplicate?title=${encodeURIComponent(prompt.title)}&version=${encodeURIComponent(prompt.version)}`);
      if (checkResponse.ok) {
        const checkData = await checkResponse.json();
        if (checkData.exists) {
          toast({
            variant: "destructive",
            description: checkData.message,
            duration: 3000,
          });
          setIsSubmitting(false);
          return;
        }
      }

      // 事务式：一次调用，后端负责创建模型与提示词
      const payload = {
        prompt: {
          ...prompt
        },
        model: {
          ...modelConfig,
          temperature: Number(modelConfig.temperature),
          max_tokens: Number(modelConfig.max_tokens),
          top_p: Number(modelConfig.top_p),
          presence_penalty: Number(modelConfig.presence_penalty),
          frequency_penalty: Number(modelConfig.frequency_penalty),
          n: Number(modelConfig.n),
          stop: modelConfig.stop ? modelConfig.stop.split(',').map(s => s.trim()).filter(Boolean) : null,
          logit_bias: modelConfig.logit_bias ? JSON.parse(modelConfig.logit_bias) : null,
          stream: Boolean(modelConfig.stream)
        }
      };

      const res = await fetch('/api/prompts/createPrompts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        throw new Error('Failed to create prompt');
      }

      router.push('/prompts');
    } catch (error) {
      console.error('Error creating prompt:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const tagSelectProps = {
    isCreatable: true,
    onKeyDown: (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        e.stopPropagation();
        
        const inputValue = e.target.value;
        if (inputValue) {
          tagSelectProps.onCreateOption(inputValue);
        }
      }
    },
    onCreateOption: async (inputValue) => {
      try {
        const response = await fetch('/api/tags', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ name: inputValue }),
        });
        
        if (response.ok) {
          const newOption = { value: inputValue, label: inputValue };
          setTagOptions([...tagOptions, newOption]);
          
          const newTags = prompt.tags ? `${prompt.tags},${inputValue}` : inputValue;
          setPrompt({ ...prompt, tags: newTags });
        }
      } catch (error) {
        console.error('Error creating new tag:', error);
      }
    }
  };

  const handleOptimize = async () => {
    if (!prompt.content.trim()) return;
    setIsOptimizing(true);
    setOptimizedContent('');
    setShowOptimizeModal(true);
    
    try {
      const response = await fetch('/api/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text: prompt.content }),
      });
      
      if (!response.ok) throw new Error(tp.optimizeError);
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let tempContent = '';
      let isStreamComplete = false;

      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          isStreamComplete = true;
          break;
        }
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter(line => line.trim());
        
        for (const line of lines) {
          try {
            const jsonStr = line.replace(/^data: /, '').trim();
            if (!jsonStr || jsonStr === '[DONE]') {
              isStreamComplete = true;
              continue;
            }
            
            const data = JSON.parse(jsonStr);
            if (data.choices?.[0]?.delta?.content) {
              tempContent += data.choices[0].delta.content;
              setOptimizedContent(tempContent);
            }
          } catch (e) {
            console.error(tp.optimizeParsingError, e);
          }
        }
      }

      // 确保流式输出完成
      if (isStreamComplete) {
        setIsOptimizing(false);
      }

    } catch (error) {
      console.error(tp.optimizationErrorLog, error);
      toast({
        variant: "destructive",
        description: tp.optimizeError,
        duration: 3000,
      });
      setIsOptimizing(false);
    }
  };

  const handleApplyOptimized = () => {
    setPrompt(prev => ({
      ...prev,
      content: optimizedContent
    }));
    setShowOptimizeModal(false);
  };

  return (
    <>
      <motion.div 
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="container mx-auto p-6 max-w-7xl"
      >
        <h1 className="text-3xl font-bold mb-6">{tp.title}</h1>
        <Card>
          <CardContent className="pt-6">
            <form onSubmit={handleSubmit} className="space-y-6">
              <motion.div 
                className="space-y-2"
                whileHover={{ scale: 1.01 }}
                transition={{ duration: 0.2 }}
              >
                <Label htmlFor="title" className="text-base">
                  {tp.formTitleLabel}
                  <span className="text-red-500 ml-1">*</span>
                </Label>
                <Input
                  id="title"
                  value={prompt.title}
                  onChange={(e) => setPrompt({ ...prompt, title: e.target.value })}
                  placeholder={tp.formTitlePlaceholder}
                  className={errors.title ? 'border-red-500' : ''}
                  required
                />
                {errors.title && (
                  <span className="text-red-500 text-sm">{errors.title}</span>
                )}
              </motion.div>

              <motion.div 
                className="space-y-2"
                whileHover={{ scale: 1.01 }}
                transition={{ duration: 0.2 }}
              >
                <Label htmlFor="content" className="text-base">
                  {tp.formContentLabel}
                  <span className="text-red-500 ml-1">*</span>
                </Label>
                <div className="relative">
                  <Textarea
                    id="content"
                    value={prompt.content}
                    onChange={(e) => setPrompt({ ...prompt, content: e.target.value })}
                    placeholder={tp.formContentPlaceholder}
                    className={`min-h-[250px] pr-12 ${errors.content ? 'border-red-500' : ''}`}
                    required
                  />
                  <Button
                    type="button"
                    size="icon"
                    variant="ghost"
                    className="absolute right-2 top-2 hover:bg-primary/10"
                    onClick={handleOptimize}
                    disabled={isOptimizing || !prompt.content.trim()}
                  >
                    {isOptimizing ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Wand2 className="h-4 w-4" />
                    )}
                  </Button>
                </div>
                {errors.content && (
                  <span className="text-red-500 text-sm">{errors.content}</span>
                )}
              </motion.div>

              <motion.div 
                className="space-y-2"
                whileHover={{ scale: 1.01 }}
                transition={{ duration: 0.2 }}
              >
                <Label htmlFor="description" className="text-base">{tp.formDescriptionLabel}</Label>
                <Textarea
                  id="description"
                  value={prompt.description}
                  onChange={(e) => setPrompt({ ...prompt, description: e.target.value })}
                  placeholder={tp.formDescriptionPlaceholder}
                  className="min-h-[80px]"
                />
              </motion.div>

              <div 
                className="space-y-2"
              >
                <Label htmlFor="tags" className="text-base">{tp.formTagsLabel}</Label>
                <CreatableSelect
                  key="tags-select"
                  id="tags"
                  isMulti
                  value={prompt.tags && prompt.tags.trim() !== '' ? 
                    prompt.tags.split(',').map(tag => ({ value: tag.trim(), label: tag.trim() })) : 
                    []
                  }
                  onChange={(selected) => {
                    const tags = selected ? selected.map(option => option.value).join(',') : '';
                    setPrompt({ ...prompt, tags });
                  }}
                  options={tagOptions}
                  placeholder={tp.formTagsPlaceholder}
                  className="basic-multi-select"
                  classNamePrefix="select"
                  {...tagSelectProps}
                  instanceId="tags-select"
                />
              </div>

              <motion.div 
                className="space-y-2"
                whileHover={{ scale: 1.01 }}
                transition={{ duration: 0.2 }}
              >
                <Label htmlFor="version" className="text-base">{tp.formVersionLabel}</Label>
                <Input
                  id="version"
                  value={prompt.version}
                  onChange={(e) => setPrompt({ ...prompt, version: e.target.value })}
                  placeholder={tp.formVersionPlaceholder}
                />
                <p className="text-sm text-muted-foreground">{tp.versionSuggestion}</p>
              </motion.div>

              <motion.div 
                className="space-y-2"
                whileHover={{ scale: 1.01 }}
                transition={{ duration: 0.2 }}
              >
                <div className="flex items-center justify-between cursor-pointer select-none" onClick={() => setShowModelConfig(!showModelConfig)}>
                  <Label className="text-base">模型配置<span className="text-red-500 ml-1">*</span></Label>
                  <span className="text-sm text-muted-foreground">{showModelConfig ? '折叠' : '展开'}</span>
                </div>
                {showModelConfig && (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border rounded-md p-4">
                    <div>
                      <Label>
                        渠道名称
                        <span className="text-red-500 ml-1">*</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>渠道名称</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <select
                        className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                        value={modelConfig.channel}
                        onChange={e => {
                          const selectedChannel = channels.find(ch => ch.name === e.target.value);
                          setModelConfig({ 
                            ...modelConfig, 
                            channel: e.target.value,
                            channel_id: selectedChannel ? selectedChannel.id : null,
                            model: '' // 清空模型选择
                          });
                        }}
                        required
                      >
                        <option value="">选择渠道</option>
                        {channels.map(channel => (
                          <option key={channel.id} value={channel.name}>
                            {channel.name}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <Label>
                        模型名称
                        <span className="text-red-500 ml-1">*</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>选择渠道后获取可用模型列表</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <select
                        className={`block w-full rounded-md border border-input bg-background px-3 py-2 text-sm ${!modelConfig.channel_id ? 'opacity-50 cursor-not-allowed' : ''}`}
                        value={modelConfig.model}
                        onChange={e => setModelConfig({ ...modelConfig, model: e.target.value })}
                        disabled={!modelConfig.channel_id}
                        required
                      >
                        <option value="">{modelConfig.channel_id ? '选择模型' : '请先选择渠道'}</option>
                        {models.map(model => (
                          <option key={model.model} value={model.model}>
                            {model.model}
                          </option>
                        ))}
                      </select>
                    </div>
                    

                    <div>
                      <Label>
                        temperature
                        <span className="text-red-500 ml-1">*</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>控制输出随机性：值越高越随机，值越低越确定，取值范围 [0, 2]</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input required type="number" step="0.1" min={0} max={2} value={modelConfig.temperature} onChange={e => setModelConfig({ ...modelConfig, temperature: e.target.value })} />
                    </div>
                    <div>
                      <Label>
                        max_tokens
                        <span className="text-red-500 ml-1">*</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>生成内容的最大 token 数量（[10, 30000]，默认 2048）</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input required type="number" min={10} max={30000} value={modelConfig.max_tokens} onChange={e => setModelConfig({ ...modelConfig, max_tokens: e.target.value })} />
                    </div>
                    <div>
                      <Label>
                        top_p
                        <span className="text-red-500 ml-1">*</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>核采样，仅考虑累积概率达到阈值的 token，取值范围 [0, 2]</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input required type="number" step="0.1" min={0} max={2} value={modelConfig.top_p} onChange={e => setModelConfig({ ...modelConfig, top_p: e.target.value })} />
                    </div>
                    <div>
                      <Label>
                        presence_penalty
                        <span className="text-red-500 ml-1">*</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>鼓励新话题：正值增加新主题概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input required type="number" step="0.1" min={-2} max={2} value={modelConfig.presence_penalty} onChange={e => setModelConfig({ ...modelConfig, presence_penalty: e.target.value })} />
                    </div>
                    <div>
                      <Label>
                        frequency_penalty
                        <span className="text-red-500 ml-1">*</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>惩罚重复：正值降低重复内容概率，负值减少，取值范围 [-2, 2]</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input required type="number" step="0.1" min={-2} max={2} value={modelConfig.frequency_penalty} onChange={e => setModelConfig({ ...modelConfig, frequency_penalty: e.target.value })} />
                    </div>
                    <div>
                      <Label>
                        n
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>生成多个独立回复（如 n=3 返回 3 个选项），用于结果多样性选择</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input type="number" value={modelConfig.n} onChange={e => setModelConfig({ ...modelConfig, n: e.target.value })} />
                    </div>
                    <div>
                      <Label>
                        stop (逗号分隔)
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>设置停止词，遇到即终止生成（如 ["\n", "。"]）</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input value={modelConfig.stop} onChange={e => setModelConfig({ ...modelConfig, stop: e.target.value })} />
                    </div>
                    <div>
                      <Label>
                        logit_bias (JSON)
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>{'调整特定 token 的生成概率（如 {"1234": 2.0}）'}</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <Input value={modelConfig.logit_bias} onChange={e => setModelConfig({ ...modelConfig, logit_bias: e.target.value })} placeholder='{"123": -5}' />
                    </div>
                    <div>
                      <Label>
                        stream
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <HelpCircle className="inline-block h-3.5 w-3.5 ml-1 text-muted-foreground" />
                            </TooltipTrigger>
                            <TooltipContent>启用流式传输，逐块返回结果</TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </Label>
                      <select
                        className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                        value={modelConfig.stream ? 'true' : 'false'}
                        onChange={e => setModelConfig({ ...modelConfig, stream: e.target.value === 'true' })}
                      >
                        <option value="false">false</option>
                        <option value="true">true</option>
                      </select>
                    </div>
                    <div>
                      <Label>api_key</Label>
                      <Input value={modelConfig.api_key} onChange={e => setModelConfig({ ...modelConfig, api_key: e.target.value })} />
                    </div>
                  </div>
                )}
              </motion.div>

              <motion.div 
                className="flex gap-4"
                whileHover={{ scale: 1.01 }}
                transition={{ duration: 0.2 }}
              >
                <Button 
                  type="submit" 
                  disabled={isSubmitting}
                  className="relative"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      {tp.creating}
                    </>
                  ) : tp.create}
                </Button>
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => router.back()}
                >
                  {tp.cancel}
                </Button>
              </motion.div>
            </form>
          </CardContent>
        </Card>
      </motion.div>

      <Modal isOpen={showOptimizeModal} onClose={() => setShowOptimizeModal(false)}>
        <ModalContent className="max-w-3xl max-h-[80vh]">
          <ModalHeader>
            <ModalTitle>{tp.optimizePreviewTitle}</ModalTitle>
          </ModalHeader>
          <div className="relative min-h-[200px] max-h-[50vh] overflow-y-auto">
            <Textarea
              value={optimizedContent}
              onChange={(e) => setOptimizedContent(e.target.value)}
              className="min-h-[200px] w-full"
              placeholder={tp.optimizePlaceholder}
            />
          </div>
          <ModalFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setShowOptimizeModal(false)}
              className="mr-2"
            >
              {tp.cancel}
            </Button>
            <Button
              type="button"
              onClick={handleApplyOptimized}
              disabled={!optimizedContent.trim() || isOptimizing}
            >
              {isOptimizing ? '优化中...' : tp.applyOptimization}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  );
}